// @ts-ignore
import {exportAllUser, opsUserById, queryUserByPage} from '@/services/ant-design-pro/userController';
import {ActionType, PageContainer, ProTable, TableDropdown} from '@ant-design/pro-components';
import { ProFormInstance } from '@ant-design/pro-form/lib';
import React, {useRef, useState} from 'react';
import {Avatar, Button, message, Modal} from "antd";
import {useModel} from "@@/exports";
import {exportInterface} from "@/services/ant-design-pro/interfaceInfoController";
import {exportExcel} from "@/common/ExcelUtils";

interface OpsDetail {
  id?:string,
  title?:string,
  userAccount?:string,
  message?:string,
  opsType:string
}

enum UserRoleEnum {
  ADMIN = "admin",
  USER = "user",
  BAN = "ban"
}

enum OpsType {
  ban = "ban",
  unseal = "unseal"
}

const Index: React.FC = () => {

  const actionUserRef = useRef<ActionType>();
  const { initialState, setInitialState } = useModel('@@initialState');

  /**
   * 封禁用户相关
   * ----------------------
   */
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [opsDetail,setOpsDetail] = useState<OpsDetail>()
  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleOpsOk = async () => {
    const res = await opsUserById({
      opsUserId:opsDetail?.id,
      opsType:opsDetail?.opsType
    })
    if (res?.code === 200){
      message.success("操作成功")
      actionUserRef?.current?.reload()
      setIsModalOpen(false);
      return;
    }
    message.error(res?.message)
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const userOperation = (key:string,record:API.UserEntity) => {

    let message;
    if (key === OpsType.ban){
      message = "封禁该用户后将禁止他的一切行为!";
    }
    if (key === OpsType.unseal){
      message = "解封该用户将恢复她的一切行为";
    }
    setOpsDetail({
      id: record?.id,
      title: record?.userName,
      userAccount:record?.userAccount,
      message: message,
      opsType:key
    })
    showModal()
  }

  const getTableItemOption = (record:API.UserEntity) => {

    let itemOption = [
      { key: OpsType.ban, name: '封禁' },
      { key: OpsType.unseal, name: '解封' },
    ]
    if (record?.userRole === UserRoleEnum.USER){
      itemOption = itemOption.filter(option=>{
        return option?.key === OpsType.ban
      })
    }
    if (record?.userRole === UserRoleEnum.BAN){
      itemOption = itemOption.filter(option=>{
        return option?.key === OpsType.unseal
      })
    }
    if (record?.id === initialState?.currentUser?.id){
      itemOption = []
    }

    return itemOption
  }

  const columns = [
    {
      title: '账号',
      dataIndex: 'userAccount',
      valueType: 'textarea',
      ellipsis: true,
      copyable: true,
    },
    {
      title: '用户名',
      dataIndex: 'userName',
      valueType: 'textarea',
      ellipsis: true
    },
    {
      title: '角色',
      width: 100,
      dataIndex: 'userRole',
      valueEnum: {
        admin: { text: '管理员', status: 'Success' },
        user: { text: '用户', status: 'Processing' },
        ban: { text: 'BAN', status: 'Error' },
      },
    },
    {
      title: '性别',
      width: 80,
      dataIndex: 'gender',
      hideInSearch: true,
      valueEnum: {
        0: { text: '未知', status: 'Default' },
        1: { text: '男性', status: 'Warning' },
        2: { text: '女性', status: 'Error' },
      },
    },
    {
      title: '头像',
      width: 80,
      dataIndex: 'userAvatar',
      valueType: 'textarea',
      hideInSearch: true,
      ellipsis: true,
      tip: '标题过长会自动收缩',
      render:(text:any,record:any)=>{
        return <Avatar src={record?.userAvatar}/>
      }
    },
    {
      title: '简介',
      dataIndex: 'userProfile',
      valueType: 'textarea',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      ellipsis: true
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      ellipsis: true
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',

      render: (text:string, record:API.UserEntity, _:any, action:any) => [
        // <a
        //   key="editable"
        //   // onClick={() => {
        //   //   action?.startEditable?.(record.id);
        //   // }}
        // >
        //   编辑
        // </a>,
        // <a href={record.url} target="_blank" rel="noopener noreferrer" key="view">
        //   查看
        // </a>,
        <TableDropdown
          key="actionGroup"
          onSelect={(key) => userOperation(key,record)}
          menus={getTableItemOption(record)}
        />,
      ],
    },
  ];

  const formUserRef = useRef<ProFormInstance>();
  const [pageRequest, setPageRequest] = useState<PageRequest>({
    current:1,
    pageSize:10
  });
  const queryUserByPager = async (
    // 第一个参数 params 查询表单和 params 参数的结合
    // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
    params:PageRequest,
  ) => {
    // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
    // 如果需要转化参数可以在这里进行修改
    setPageRequest({
      current:params?.current,
      pageSize:params?.pageSize
    })
    const searchParam = formUserRef?.current?.getFieldsValue();
    const msg = await queryUserByPage({
      // pageIndex: params.current,
      // pageSize: params.pageSize,
      ...params,
      ...searchParam,
    });
    return {
      data: msg?.data?.records,
      // success 请返回 true，
      // 不然 table 会停止解析数据，即使有数据
      success: msg?.code === 200,
      // 不传会使用 data 的长度，如果是分页一定要传
      total: msg?.data?.total,
    };
  };

  /**
   * 导出所有用户
   */
  const exportUserAll = async () => {

    const res = await exportAllUser({
      responseType:"blob"
    })
    let blob = new Blob([res]); //res为从后台返回的数据
    let fileName = "用户.xlsx";
    exportExcel(fileName,blob)
  }

  return (
    <PageContainer
      // content="欢迎使用 ProLayout 组件"
      breadcrumbRender={false}
      header={{ title: undefined }}
      // breadcrumbRender={false}
      // tabList={[
      //   {
      //     tab: '基本信息',
      //     key: 'base',
      //   },
      //   {
      //     tab: '详细信息',
      //     key: 'info',
      //   },
      // ]}
      // extra={[
      //   <Button key="3">操作</Button>,
      //   <Button key="2">操作</Button>,
      //   <Button key="1" type="primary">
      //     主操作
      //   </Button>,
      // ]}
    >
      <ProTable<API.InterfaceInfoEntity, any>
        // params 是需要自带的参数
        // 这个参数优先级更高，会覆盖查询表单的参数
        headerTitle="用户管理"
        formRef={formUserRef}
        actionRef={actionUserRef}
        params={{}}
        columns={columns as any}
        pagination={pageRequest}
        rowKey="id"
        toolBarRender={() => [
          <Button key="add" type={'primary'} onClick={exportUserAll}>
            导出
          </Button>
        ]}
        search={{
          labelWidth: 100,
          span: 6,
        }}
        request={(params) => queryUserByPager(params)}
      />

      <Modal title={opsDetail?.title} open={isModalOpen} onOk={handleOpsOk} onCancel={handleCancel}>
        <p>{opsDetail?.userAccount}</p>
        <p>{opsDetail?.message}</p>
      </Modal>
    </PageContainer>
  );
};

export default Index;
